package menu

import (
	"context"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/utils/parse"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuListByRoleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetMenuListByRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuListByRoleLogic {
	return &GetMenuListByRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetMenuListByRoleLogic) GetMenuListByRole() (resp *types.SystemMenuListResp, err error) {
	var roles string = l.ctx.Value("roles").(string)
	if len(roles) == 0 {
		return &types.SystemMenuListResp{}, nil
	}

	page, pageSize := parse.ParsePageInfo(
		nil,
		pointy.GetPointer(int64(0)),
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	data, err := l.svcCtx.BackendRpc.GetMenuList(l.ctx, &backendclient.MenuListReq{
		Page:     page,
		PageSize: pageSize,
		Roles:    pointy.GetPointer(roles),
	})
	if err != nil {
		return
	}

	resp = &types.SystemMenuListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.SystemMenuListInfo{
			BaseListInfo: types.BaseListInfo{
				Total: data.GetTotal(),
			},
		},
	}
	for _, v := range data.List {
		resp.Data.List = append(resp.Data.List, &types.SystemMenuInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        v.Id,
				CreatedAt: v.CreatedAt,
				UpdatedAt: v.UpdatedAt,
			},
			Path:      v.Path,
			Redirect:  v.Redirect,
			Name:      v.Name,
			Icon:      v.Icon,
			ParentId:  v.ParentId,
			Component: v.Component,
			Status:    v.Status,
			Sort:      v.Sort,
		})
	}

	return resp, nil
}
